#include "QNetDebug.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QByteArray>
#include <QDebug>

QNetDebug::QNetDebug(QObject *parent)
    : QObject(parent),
      m_socket(nullptr),
      m_serverAddress(QHostAddress("192.168.1.74"))
{
}
QNetDebug::~QNetDebug()
{
    if (m_socket) {
        delete m_socket;
        m_socket = nullptr;
    }
}

bool QNetDebug::init(const QString &serverAddress, quint16 serverPort)
{
    // Clean up any existing socket
    if (m_socket) {
        delete m_socket;
    }

    // Create new UDP socket
    m_socket = new QUdpSocket(this);

    // Set server address and port
    m_serverAddress = QHostAddress(serverAddress);
    m_serverPort = serverPort;

    return true;
}

void QNetDebug::kgWrite(const QString &message)
{
    sendMessage("INFO", message);
}

void QNetDebug::info(const QString &message)
{
    sendMessage("INFO", message);
}

void QNetDebug::warning(const QString &message)
{
    sendMessage("WARNING", message);
}

void QNetDebug::error(const QString &message)
{
    sendMessage("ERROR", message);
}

void QNetDebug::debug(const QString &message)
{
    sendMessage("DEBUG", message);
}

void QNetDebug::sendMessage(const QString &prefix, const QString &message)
{
    if (!m_socket) {
        qWarning() << "QNetDebug: Socket not initialized. Call init() first.";
        return;
    }

    // Create JSON message
    QJsonObject jsonMsg;
    jsonMsg["type"] = prefix;
    jsonMsg["app"] = m_appName;
    jsonMsg["message"] = message;

    if (m_timestampEnabled) {
        jsonMsg["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);
    }

    QJsonDocument doc(jsonMsg);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    // Send the message
    qint64 sent = m_socket->writeDatagram(data, m_serverAddress, m_serverPort);

    if (sent != data.size()) {
        qWarning() << "QNetDebug: Failed to send full message, sent" << sent << "bytes of" << data.size();
    }
}

QHostAddress QNetDebug::serverAddress() const
{
    return m_serverAddress;
}

void QNetDebug::setServerAddress(const QHostAddress &address)
{
    m_serverAddress = address;
}

quint16 QNetDebug::serverPort() const
{
    return m_serverPort;
}

void QNetDebug::setServerPort(quint16 port)
{
    m_serverPort = port;
}

QString QNetDebug::applicationName() const
{
    return m_appName;
}

void QNetDebug::setApplicationName(const QString &name)
{
    m_appName = name;
}

bool QNetDebug::timestampEnabled() const
{
    return m_timestampEnabled;
}

void QNetDebug::setTimestampEnabled(bool enabled)
{
    m_timestampEnabled = enabled;
}
